﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using SSHTool.Core.Message;
using SSHTool.Model;
using SSHTool.Service;
using SSHTool.Util;
using SSHTool.View;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;

namespace SSHTool.ViewModel
{
    public class FileMgrViewModel : ObservableObject, IDialogResultable<int>
    {
        private FileService fileService;
        private AuthService authService;
        private SshService sshService;
        public FileMgrViewModel(FileService fileService, AuthService authService)
        {
            this.fileService = fileService;
            this.authService = authService;
        }

        private int connectionId = 0;

        private bool addRowFlag = false;

        public bool AddRowFlag { get => addRowFlag; set => SetProperty(ref addRowFlag, value); }

        private bool readOnly = true;

        public bool ReadOnly { get => readOnly; set => SetProperty(ref readOnly, value); }

        private string item1Title;

        public string Item1Title { get => item1Title; set => SetProperty(ref item1Title, value); }

        private ObservableCollection<FileViewModel> fileList;

        public ObservableCollection<FileViewModel> FileList { get => fileList; set => SetProperty(ref fileList, value); }

        private int result;
        public int Result { get => result; set => SetProperty(ref result, value); }

        public Action CloseAction { get; set; }

        public RelayCommand SureCmd => new RelayCommand(() =>
        {
            UnRegisterMsg();
            CloseAction?.Invoke();
        });

        public RelayCommand CancelCmd => new RelayCommand(() =>
        {
            Result = 0;
            UnRegisterMsg();
            CloseAction?.Invoke();
        });

        public RelayCommand<AddingNewItemEventArgs> AddNewFileCmd => new RelayCommand<AddingNewItemEventArgs>(AddNewFile);

        public RelayCommand<DataGridRowEditEndingEventArgs> EditFileCmd => new RelayCommand<DataGridRowEditEndingEventArgs>(EditFile);

        public RelayCommand<FileViewModel> EditFileContentCmd => new RelayCommand<FileViewModel>(EditFileContent);

        public RelayCommand<FileViewModel> AddVariableCmd => new RelayCommand<FileViewModel>(AddVariable);

        public void Init(int connectionId, SshService sshService)
        {
            this.connectionId = connectionId;
            this.sshService = sshService;

            RegisterMsg();

            AddRowFlag = authService.IsAdmin();
            ReadOnly = !AddRowFlag;
            Item1Title = ReadOnly ? "查看文件" : "编辑文件";

            var list = fileService.GetFileList(connectionId);

            FileList = StringUtil.CopyViewList<FileModel, FileViewModel>(list);
        }

        private void AddNewFile(AddingNewItemEventArgs e)
        {
            int maxId = 0;

            if (fileList.Count > 0)
            {
                maxId = fileList.Max(m => m.Id);
            }

            maxId++;

            FileViewModel model = new FileViewModel
            {
                Id = maxId,
                Type = Constant.FILE_TYPE_COMMON
            };

            e.NewItem = model;
        }

        private void EditFile(DataGridRowEditEndingEventArgs e)
        {
            if (e.EditAction == DataGridEditAction.Commit)
            {
                if (e.Row.DataContext is FileViewModel vm)
                {
                    if (string.IsNullOrEmpty(vm.Name))
                    {
                        Growl.Warning("文件名称不能为空");
                        return;
                    }

                    if (!(vm.Type == Constant.FILE_TYPE_COMMON || vm.Type == Constant.FILE_TYPE_KEY_VALUE))
                    {
                        Growl.Warning("文件类型只能为[0=普通类型,1=Key-Value类型]");
                        return;
                    }

                    if (string.IsNullOrEmpty(vm.Path))
                    {
                        Growl.Warning("文件路径不能为空");
                        return;
                    }

                    vm.FileName = FileUtil.GetFileName(vm.Path);

                    fileService.Update(FileList);

                    Growl.Success("歌曲更新成功!");
                }
            }
        }

        private async void EditFileContent(FileViewModel model)
        {
            if (model == null)
            {
                return;
            }

            string fileContent = sshService.GetContent(model.Path);

            var vm = App.GetService<EditFileViewModel>();
            var content = App.GetService<EditFileControl>();

            vm.Title = $"{Item1Title} [{model.Path}]";
            vm.RichText = fileContent;
            vm.Path = model.Path;
            vm.ReadOnly = ReadOnly;

            content.DataContext = vm;

            var result = await Dialog.Show(content).GetResultAsync<int>();

            if (result == 1)
            {
                sshService.WriteContent(model.Path, vm.RichText);
            }
        }

        private void AddVariable(FileViewModel model)
        {
            if (model == null)
            {
                return;
            }

            if (model.Type != Constant.FILE_TYPE_KEY_VALUE)
            {
                Growl.Warning("只有文件类型为[1=Key-Value]才能添加常用变量");
                return;
            }


        }

        private void RegisterMsg()
        {
            WeakReferenceMessenger.Default.Register<SaveFileContentMessage>(this, (o, args) =>
            {
                sshService.WriteContent(args.Path, args.Value);
            });
        }

        private void UnRegisterMsg()
        {
            WeakReferenceMessenger.Default.Unregister<SaveFileContentMessage>(this);
        }
    }
}
